package com.blog.controller;

import com.blog.domain.ResponseResult;
import com.blog.domain.entity.Menu;
import com.blog.domain.vo.MenuTreeVo;
import com.blog.domain.vo.MenuVo;
import com.blog.domain.vo.RoleMenuTreeVo;
import com.blog.service.MenuService;
import com.blog.service.RoleService;
import com.blog.utils.BeanCopyUtils;

import com.blog.utils.SystemConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("system/menu")
public class MenuController {

	@Autowired
	private MenuService menuService;


	@Autowired
	private RoleService roleService;

	/**菜单查询
	 *
	 * @param status 状态
	 * @param menuName  菜单名
	 * @return
	 */

	@GetMapping("/list")
	public ResponseResult menuList(String status, String menuName){

		List<Menu> menus = menuService.menuList(status, menuName);
		List<MenuVo> menuVos = BeanCopyUtils.copyBeanList(menus, MenuVo.class);
		return ResponseResult.okResult(menuVos);
	}
	/**新增菜单
	 *
	 * @param menu
	 * @return
	 */
	@PostMapping
	public ResponseResult addMenu(@RequestBody Menu menu){
		return menuService.addMenu(menu);
	}

	/**菜单详情回显
	 *
	 * @param id
	 * @return
	 */
	@GetMapping("/{id}")
	public ResponseResult getMenuDetailById(@PathVariable  Long id){

		return menuService.getMenuDetailById(id);

	}

	/**更新菜单
	 *
	 * @param menu
	 * @return
	 */
	@PutMapping
	public ResponseResult updateMenu(@RequestBody Menu menu){

		return menuService.updateMenu(menu);

	}

	/**删除菜单
	 *
	 * @param menuId
	 * @return
	 */
	@DeleteMapping("/{menuId}")
	public ResponseResult deleteMenu(@PathVariable Long menuId){
		return menuService.deleteMenu(menuId);
	}

	/**获取菜单树接口
	 *
	 * @return
	 */
	@GetMapping("/treeselect")
	public ResponseResult menuTreeList(){

		List<Menu> menus = menuService.menuList(null, null);
		List<MenuTreeVo> options =  SystemConverter.buildMenuSelectTree(menus);
		return ResponseResult.okResult(options);
	}

	/**对应角色的菜单列表
	 *
	 * @param id
	 * @return
	 */


	@GetMapping("/roleMenuTreeselect/{id}")
	public ResponseResult<RoleMenuTreeVo> menuTreeToRole(@PathVariable Long id){

		//查询所有的菜单
		List<Menu> menus = menuService.menuList(null, null);
		//根据角色id查询角色对应的菜单id
		List<Long> checkedKeys = roleService.getRoleAllMenuId(id);
		//构建树形结构（此过程将不属于角色的菜单过滤掉，只剩属于角色的菜单）
		List<MenuTreeVo> menuTreeVos = SystemConverter.buildMenuSelectTree(menus);
		//封装数据Vo返回结果
		RoleMenuTreeVo roleMenuTreeVo = new RoleMenuTreeVo(menuTreeVos, checkedKeys);


		return ResponseResult.okResult(roleMenuTreeVo);
	}
}
